<template>
	<view class="container" ref="container" :style="`height:` + windowHeight + `px`">
		<map class="map" id="myMap" :scale="getScaleValue" :min-scale="8" :latitude="latitude" :longitude="longitude"
			:markers="markers" theme="satellite" show-location @labeltap="onMarkerTap" @regionchange="onRegionChange">
			<!-- <markers>
				<marker v-for="(marker, index) in markers" :key="index" :id="marker.id" :latitude="marker.latitude"
					:longitude="marker.longitude" :iconPath="marker.iconPath" :z-index="marker.zIndex">
					<label :content="marker.name" :color="'#000000'" :bgColor="'#ffffff'" :width="68" :height="68"
						display="ALWAYS" />
				</marker>
			</markers> -->
		</map>
		<uni-popup ref="popup" type="bottom" :safeArea="0">
			<view class="popBox">
				<view class="title">{{ activeDistrictArea }}</view>
				<view class="num">可租{{ emptyNum }}/{{ totalNum }}套</view>
				<view class="roomList">
					<mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback">
						<view class="list row" v-for="(item, index) in roomList" :key="index" @tap="handleRoomDetail(item)">
							<view class="pic">
								<image class="img" v-if="item.picUrl" :src="item.picUrl" mode=""></image>
								<image class="img" v-else :src="$imgUrl + '/index/room.png'" mode=""></image>
							</view>
							<view class="mess">
								<view class="name line1">{{ item.roomFullName }}</view>
								<view class="area line1">{{ item.roomHouseTypeName }} | {{ item.space }}㎡</view>
								<view class="addr line1"><text class="icon-addr"></text>{{ item.address }}</view>
								<view class="price"><text class="yellow">{{ item.monthRental || 0 }}</text>/月起</view>
							</view>
						</view>
					</mescroll-body>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script lang="ts" setup>
// 工具
import { ref, nextTick, onMounted, getCurrentInstance } from 'vue'
import { onHide, onPageScroll, onReachBottom } from '@dcloudio/uni-app'
import { MapContext } from 'weixin-app'
import useMescroll from '@/uni_modules/mescroll-uni/hooks/useMescroll.js'
const { mescrollInit, downCallback } = useMescroll(onPageScroll, onReachBottom)

import {
	mapfindroom,
	mapfindroom2,
	getapartmentareainfo,
} from '@/common/API/room'
import config from '@/utils/config'

const windowHeight = ref(0) // 屏幕高度
const latitude = ref(31.86119) //初始化当前纬度
const longitude = ref(117.283042) //初始化当前经度
const getScaleValue = ref(15) // 调用组件获取到的缩放级别
const maxLongitude = ref() //视角最大经度
const minLongitude = ref() //视角最小经度
const maxLatitude = ref() //视角最大纬度
const minLatitude = ref() //视角最小纬度

const isCreateMarker = ref(false) // 控制 markerCreate
const activeDistrict = ref('') //当前查询的区
const activeStreet = ref('') //当前选择的街道
const activeDistrictArea = ref('') // 房源小区
const markerTapFlag = ref(false)
const roomList = ref([]) // 某小区的房源列表
const emptyNum = ref(0) // 空房数量
const totalNum = ref(0) // 房源总数量

const markers = ref([])
const mapContext = ref<MapContext | null>(null)
const container = ref()

const handleRoomDetail = (val) => {
	uni.navigateTo({
		url: `/pages/searchRoom/disperseHouseDetail?roomHouseId=${val.roomHouseId}`,
	})
}

const _getScale = () => {
	return new Promise((resolve, reject) => {
		mapContext.value.getScale({
			success: (res) => {
				console.log('_getScale----success', res)
				resolve(res.scale)
			},
			fail: (err) => {
				console.log('getScale----Err', err)
			},
		})
	})
}
const _getRegion = () => {
	return new Promise((resolve, reject) => {
		mapContext.value?.getRegion({
			success: (res) => {
				// 	console.log('getRegionRes:--------' + JSON.stringify(res))
				// maxLongitude.value = res.northeast.longitude
				// minLongitude.value = res.southwest.longitude
				// maxLatitude.value = res.northeast.latitude
				// minLatitude.value = res.southwest.latitude
				resolve(res)
			},
			fail: (err) => {
				console.log('getRegion-----Err', err)
			},
		})
	})
}
const removeMarkersFn = () => {
	console.log(
		'removeMarkersFn------------------start222',
		!markers.value.length
	)
	if (!markers.value.length) {
		return Promise.resolve()
	}
	// 清除marker
	return new Promise((resolve) => {
		// #ifdef MP-WEIXIN
		mapContext?.value.removeMarkers({
			markerIds: markers.value.map((e) => e.id),
			success: (res) => {
				console.log('removeMarkers-----------', res)
				markers.value = []
				resolve(res)
			},
			fail: (err) => {
				console.log('removeMarkers-----------ERR', err)
			},
			complete: (res) => {
				console.log('removeMarkers-----------Complete', res)
			},
		})
		// #endif

		// #ifdef APP-PLUS
		console.log('removeMarkers===APP')
		markers.value = []
		resolve(true)
		// #endif
	})
}
const addMarkersFn = () => {
	// isCreateMarker.value = true
	mapContext.value.addMarkers({
		markers: markers.value,
		clear: true,
		success: (res) => {
			console.log('addMarkers--------', res)
			isCreateMarker.value = false

			markerTapFlag.value = false
			// 添加成功，放开控制器
			// mapContext.value.includePoints({
			// 	points:markers.value.map(e=>{
			// 		return {
			// 			latitude:e.latitude,
			// 			longitude:e.longitude
			// 		}
			// 	}),
			// 	success:()=>{
			// 		markerTapFlag.value =false
			// 	}
			// })
		},
		fail: (err) => {
			console.log('addMarkerEff--------------FFF', err)
		},
	})
}

const _getRoom = async (scale?: any) => {
	console.log('getRoom-----start', markerTapFlag.value)

	let getRegionRes = await _getRegion()
	let getScaleRes = await _getScale()
	let data = {
		zoom: scale || getScaleRes,
		maxLongitude: getRegionRes.northeast.longitude,
		minLongitude: getRegionRes.southwest.longitude,
		maxLatitude: getRegionRes.northeast.latitude,
		minLatitude: getRegionRes.southwest.latitude,
	}
	let res = await mapfindroom(data)
	console.log('getRoom------->', res, !res?.length)
	if (!res?.length) {
		markerTapFlag.value = false
		return
	}
	_creatMarker(res)
}

const throttle = (func, delay)=> {
  let timeoutId;
  let lastExecutedTime = 0;
  
  return function() {
    const currentTime = Date.now();
    const elapsedTime = currentTime - lastExecutedTime;

    if (!lastExecutedTime || elapsedTime >= delay) {
      func.apply(this, arguments);
      lastExecutedTime = currentTime;
    } else {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        func.apply(this, arguments);
        lastExecutedTime = currentTime;
      }, delay - elapsedTime);
    }
  };
}
const getRoom = throttle(_getRoom, 300)

const _creatMarker = (res) => {
	console.log('_creatMarker_____isCreateMarker', isCreateMarker.value)
	if (isCreateMarker.value === true) return
	removeMarkersFn().then(() => {
		try {

			res.forEach((item, i) => {
				markers.value.push({
					id: i + 1,
					level: item.level,
					apartmentAreaId: item.apartmentAreaId,
					district: item.district || '',
					latitude: item.latLon.split(',')[1],
					longitude: item.latLon.split(',')[0],
					iconPath: '/static/images/location.png',
					zIndex: 1,
					name: `${item.name}｜${item.num} 套`,
					width: 0.5,
					height: 0.5,
					label: {
						content: `${item.name}｜${item.num} 套`,
						color: '#ffffff',
						bgColor: '#FD9618',
						borderRadius: '4',
						padding: '6',
						anchorX: '-55',
						anchorY: '-52',
					},
				})
			})

			addMarkersFn()
		} catch (err) {
			console.log('createMarker------Err', err)
		}
	})
}

const moveToCenterLoacation = () => {
	return new Promise(async (resolve, reject) => {
		mapContext.value.getCenterLocation({
			success: ({ longitude, latitude }) => {
				mapContext.value.moveToLocation({
					longitude,
					latitude,
					success: (res) => {
						console.log('moveToCenterLoacation------->success', res)
						resolve(res)
					},
					fail: (err) => {
						console.log('moveToCenterLoacation------->Err', err)
					},
				})
			},
		})
	})
}

const getRommByDistrict = async () => {
	try {
		let data = {
			district: activeDistrict.value,
			street: activeStreet.value,
		}
		let res = await mapfindroom2(data)
		_creatMarker(res)
	} catch (err) {
		markerTapFlag.value = false
	}
}

const popup = ref()
const open = () => {
	popup.value.open('bottom')
}
const curApartmentAreaId = ref()
const onMarkerTap = (e) => {
	markerTapFlag.value = true
	let item = markers.value.find((el) => el.id === e.detail.markerId)
	console.log('onMarkerTap--------item---->',item)
	if (item.level === 1) {
				activeDistrict.value = item.label.content.split('｜')[0].trim()
				getScaleValue.value = 13.99
				getRoom(13.99)
			}
			if (item.level === 2) {
				getScaleValue.value = 15
				activeStreet.value = item.label.content.split('｜')[0].trim()
				activeDistrict.value = item.district
				getRoom(15)
			}
			if (item.level === 3) {
				activeDistrictArea.value = item.label.content.split('｜')[0].trim()
				curApartmentAreaId.value = item.apartmentAreaId
				resetScroll()
			}

	// mapContext.value.includePoints({
	//   points: markers.value.map((e) => {
	//     return {
	//       latitude: e.latitude,
	//       longitude: e.longitude,
	//     }
	//   }),
	// })
}

const onRegionChange = (e) => {
	console.log(
		'onRegionChange--------->markerTapFlag',
		e.detail,
		markerTapFlag.value
	)
	if (markerTapFlag.value === true) return
	if (e.detail.type === 'end') {
		getRoom()
	}
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance
onMounted(() => {
	nextTick(() => {
		windowHeight.value = uni.getSystemInfoSync().windowHeight
		setTimeout(() => {
			mapContext.value = uni.createMapContext('myMap', proxy)

			mapContext.value.moveToLocation({
				success: (res) => {
					console.log('moveToCenterLoacation------->onMounted', res)
					getRoom()
				},
				fail: (err) => {
					console.log('moveToCenterLoacation------->Err', err)
				},
			})
		}, 500)
	})
})

const upCallback = async (mescroll) => {
	// console.log(123)
	if (!curApartmentAreaId.value) return false
	let data = {
		pageNo: mescroll.num,
		pageSize: 10,
		apartmentAreaId: curApartmentAreaId.value,
	}
	getapartmentareainfo(data)
		.then((res) => {
			let curPageData = res.page.list
			let curPageLen = curPageData.length
			if (mescroll.num == 1) roomList.value = []
			roomList.value = roomList.value.concat(curPageData)
			emptyNum.value = res.emptyNum
			totalNum.value = res.totalNum
			markerTapFlag.value = false
			open()
			mescroll.endSuccess(curPageLen)
		})
		.catch(() => {
			markerTapFlag.value = false
		})
}

const resetScroll = () => {
	roomList.value = []
	downCallback()
}
</script>

<style lang="scss" scoped>
.container {
	.map {
		width: 100%;
		height: 100%;

		::v-deep.amap-container {
			.amap-logo {
				display: none !important;
			}

			.amap-copyright {
				display: none !important;
			}

			.amap-marker {
				// border-radius: 8rpx;
				// overflow: hidden;
			}
		}
	}

	.popBox {
		background: #fff;
		// padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		border-radius: 28rpx 28rpx 0 0;
		padding-top: 40rpx;

		.title {
			padding: 0 40rpx;
			font-size: 36rpx;
			color: #000;
			line-height: 44rpx;
		}

		.num {
			padding: 0 40rpx;
			line-height: 34rpx;
			margin: 8rpx 0 32rpx;
		}

		.roomList {
			border-top: 2rpx solid #f5f5f5;
			padding: 0 40rpx;
			max-height: 700rpx;
			overflow-y: scroll;

			.list {
				padding: 34rpx 0 20rpx;

				.pic {
					width: 242rpx;
					height: 184rpx;
					border-radius: 8rpx;
					overflow: hidden;
					margin-right: 28rpx;
				}

				.mess {
					max-width: 400rpx;

					.name {
						font-size: 30rpx;
						color: #000;
						line-height: 36rpx;
						font-weight: bold;
					}

					.area {
						color: #666;
						font-size: 24rpx;
						margin: 10rpx 0 6rpx;
					}

					.addr {
						font-size: 24rpx;
						line-height: 30rpx;
						margin: 0 0 12rpx;
						color: #999;

						.icon-addr {
							display: inline-block;
							width: 28rpx;
							height: 28rpx;
							background: url('#{$imgUrl}/index/room-addr.png') no-repeat;
							background-size: 100% 100%;
							vertical-align: middle;
							margin: -4rpx 8rpx 0 0;
						}
					}

					.price {
						margin: 14rpx 0 0;
						color: #4d4d4d;
						font-size: 20rpx;
						line-height: 40rpx;

						.yellow {
							font-size: 36rpx;
							font-weight: bold;
						}
					}
				}
			}
		}
	}
}
</style>
